package indi.zhifa.engine.core.excel2025.handler.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import indi.zhifa.engine.core.excel2025.annotation.ExcelColumnAnn;
import indi.zhifa.engine.core.excel2025.annotation.ExcelHandlerAnn;
import indi.zhifa.engine.core.excel2025.entity.IRowData;
import indi.zhifa.engine.core.excel2025.entity.exception.ExcelException;
import indi.zhifa.engine.core.excel2025.enums.EExcelErrorCode;
import indi.zhifa.engine.core.excel2025.handler.IExcelCellHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.lang.reflect.Field;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Date;

@ExcelHandlerAnn(valTypes = {LocalDateTime.class, LocalDate.class, LocalTime.class})
@Slf4j
public class TimeCellHandler implements IExcelCellHandler {

    DateTimeFormatter df;

    public TimeCellHandler() {
        df = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .append(DateTimeFormatter.ISO_LOCAL_DATE)
                .appendLiteral(' ')
                .append(DateTimeFormatter.ISO_LOCAL_TIME)
                .toFormatter();
    }

    @Override
    public Object handle(Cell pCell, Class pClass) {
        if (null == pCell) {
            return null;
        }
        String strVal = null;
        CellType cellType = pCell.getCellType();
        LocalDateTime dateTime = null;

        if (cellType == CellType.NUMERIC) {
            Date date = pCell.getDateCellValue();
            Instant instant = date.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            dateTime = instant.atZone(zoneId).toLocalDateTime();
            return dateTime;
        }

        if (cellType == CellType.STRING) {
            strVal = pCell.getStringCellValue();
        } else if (cellType == CellType._NONE || cellType == CellType.BLANK) {
            strVal = null;
        }
        if (null != strVal) {
            try {
                //2020-01-01 00:00:00
                switch (strVal.length()) {
                    case 8:
                        log.debug("传过来的是日期格式：{}", strVal);
                        strVal = strVal.replace("年","-").replace("月","-");
                        strVal = strVal + "01 00:00:00";
                        break;
                    case 10:
                        log.debug("传过来的是日期格式：{}", strVal);
                        strVal = strVal + " 00:00:00";
                        break;
                    case 13:
                        log.debug("传过来的是日期 小时格式：{}", strVal);
                        strVal = strVal + ":00:00";
                        break;
                    case 16:
                        log.debug("传过来的是日期 小时:分钟格式：{}", strVal);
                        strVal = strVal + ":00";
                        break;
                }
                dateTime = LocalDateTime.parse(strVal, df);
                return dateTime;
            } catch (Exception e) {
                throw new ExcelException(EExcelErrorCode.CELL_TYPE_FAILED, "解析时间" + strVal + "出错，请查看时间格式");
            }
        }
        if(LocalDate.class.isAssignableFrom(pClass)){
            return dateTime.toLocalDate();
        }else if(LocalTime.class.isAssignableFrom(pClass)){
            return dateTime.toLocalTime();
        }else if(LocalDateTime.class.isAssignableFrom(pClass)){
            return dateTime;
        }

        return dateTime;
    }

    @Override
    public void fill(Cell pCell, IRowData pRowData, Field pField) throws IllegalAccessException {
        Object data = pField.get(pRowData);
        if (null != data) {
            LocalDateTime sData = (LocalDateTime) data;
            ExcelColumnAnn excelColumn = pField.getAnnotation(ExcelColumnAnn.class);
            if (null != sData) {
                if (excelColumn.dateChange()) {
                    pCell.setCellValue(sData.format(DateTimeFormatter.ofPattern(excelColumn.dateFormatter())));
                } else {
                    pCell.setCellValue(sData.toString());
                }

            } else {
                log.error("对象的字段 " + pField.getName() + " 不是字符串, \n" + JSON.toJSONString(pRowData, JSONWriter.Feature.PrettyFormat));
            }
        }
    }
}
